package com.lib.common.helper.arouter.mapping;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.lib.framework.manager.ContextManager;
import com.lib.framework.utils.GsonUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by Zhangjiaxing on 2019/1/4.
 * If there are any problems, please
 * send email to kevin.zhang@xiangwushuo.com
 *
 * @descrpition
 **/
public class PathMappingFactory {

    static class Holder {
        public final static PathMappingFactory INSTANCE = new PathMappingFactory();
    }

    public static PathMappingFactory getInstance() {
        return Holder.INSTANCE;
    }

    private PathMapping mPathMapping;

    private PathMappingFactory() {
        init();
    }

    private void init() {
        mPathMapping = loadFromAssets();
    }

    private PathMapping loadFromAssets() {
        try {
            InputStream inputStream = ContextManager.applicationContext.getAssets().open("path-mapping");
            JsonParser jsonParser = new JsonParser();
            JsonObject jsonObject = jsonParser.parse(new InputStreamReader(inputStream, "UTF-8")).getAsJsonObject();
            return GsonUtil.fromJson(jsonObject.get("data"), PathMapping.class);
        } catch (IOException e) {
            mPathMapping = PathMapping.EMPTY;
            e.printStackTrace();
        }

        return PathMapping.EMPTY;
    }

    public String getPathCode(String path) {
        try {
            String code = mPathMapping.getCode(path);
            return code;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "0";

    }

    public String getPath(String code) {
        String path = mPathMapping.getPath(code);
        return path;
    }


    public PathInfo getPathInfoByCode(String code) {
        return mPathMapping.getPathInfoByCode(code);
    }
}
